package domain;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class AlternativeVector extends Vector{
	private Alternative alternative;
	private Criteria criteria;
	
	public Alternative getAlternative() {
		return alternative;
	}
	public Criteria getCriteria() {
		return criteria;
	}
	public void setAlternative(Alternative alternative) {
		this.alternative = alternative;
	}
	public void setCriteria(Criteria criteria) {
		this.criteria = criteria;
	}
	
	public void insert() throws SQLException{
		Connection conn = getConnection();
		PreparedStatement ps = null;
		 StringBuffer sql = new StringBuffer();
			 sql.append("insert into vector(priority, type, sub_criteria_id, project_id, alternative_id, criteria_id) ");
			 sql.append(" values(?, ?, ?, ?, ?, ?)");
		 int index =1;
		 ps = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
		 	ps.setDouble(index++, this.priority);
		 	ps.setString(index++, this.type);
		 	ps.setLong(index++, 0);
		 	ps.setLong(index++, 0);
		 	ps.setLong(index++, this.alternative.getId());
		 	ps.setLong(index++, this.criteria.getId());
		 	
		 ps.executeUpdate();
		 
		 ResultSet resultSet = ps.getGeneratedKeys();
			if (resultSet.next()) {
				long generatedid = resultSet.getLong(1);
				ps.close();
				conn.close();
				this.id = generatedid;
			} else {
				 System.out.println("Cannot Get Genereated ID!!!!");
			}
	}
	
	public static List<AlternativeVector> findByCriteriaId(long criteriaId) throws SQLException {
		Connection conn = getConnection();
		PreparedStatement ps = null;
		 StringBuffer sql = new StringBuffer();
			 sql.append("select id, priority, alternative_id, criteria_id from vector where criteria_id = ? ");
		 ps = conn.prepareStatement(sql.toString());
		 int index=1;
		 	ps.setLong(index++, criteriaId);
		 	
		 ResultSet rs = ps.executeQuery();
		 
		 List<AlternativeVector> pairs = new ArrayList<AlternativeVector>();
		 while(rs.next()){
			 AlternativeVector pair = new AlternativeVector();
				 pair.setId(rs.getLong("id"));
				 pair.setPriority(rs.getDouble("priority"));
				 pair.setAlternative(Alternative.find(rs.getLong("alternative_id")));
				 pair.setCriteria(Criteria.find(rs.getLong("criteria_id")));
			pairs.add(pair);
		 }
		 
		 ps.close();
		 conn.close();
		 
		 return pairs;
	}
}
